;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Account.RefundReceive", [])
        .controller("RefundReceiveCtrl", ["$scope", "ybWidget", "ybHttp", "MESG_TYPE", "UserContextService", "$timeout", "$filter", function ($scope, ybWidget, ybHttp, MESG_TYPE, UserContextService, $timeout, $filter) {
            // 请求url对象
            var UrlObj = {
                list: '/refundCheck/list',                // 退款单列表
                reverse: '/refundCheck/reverse',          // 红冲
                export: '/refundCheck/export',            // 导出
                exportAll: '/refundCheck/exportAll',      // 导出全部
                detail: ''
            };

            //请求类型对象
            var RequestTypeObj = {
                get: 'Get',
                post: 'Post'
            };

            // 和后端交互的按钮权限码
            var btnPermissionCode = {
                refundReceiveReverse: window.ActionCode.refundReceiveReverse,
                refundReceiveExport: window.ActionCode.refundReceiveExport
            };
            // 按钮权限
            $scope.btnPermission = {
                refundReceiveReverse: true,
                refundReceiveExport: true,
            };
            // tab标签展示布尔值
            $scope.activeFlag = [true, false, false];
            // checkbox 选择是否信息
            $scope.markInfo = {
                allChecked: false
            };
            // 分页信息
            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            // 高级搜索配置信息
            $scope.toolbarConfig = {};
            // 切换高级搜索展示隐藏
            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                    return;
                }
                $timeout(function () {
                    $scope.toolbarConfig["show" + toolbar] = true;
                });
            };
            // 重置搜索条件
            $scope.reset = function () {
                $scope.condition = {};
            };
            // 列表表格配置信息
            $scope.tableConfig = {
                fixedWidth: 100,
                scrollWidth: 1100,
                tableCol: [
                    {
                        name: "退款单号",
                        dataField: "refundOrder",
                        width: 160,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "退货单号",
                        dataField: "refundNo",
                        width: 160,
                        isShow: true,
                        isFixed: false,
                        type: "click",
                        clickFn: "viewDetail"
                    },
                    {
                        name: "单据总金额",
                        dataField: "totalPrice",
                        width: 120,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "折损金额",
                        dataField: "lossAmount",
                        width: 120,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "预付款退款金额",
                        dataField: "advancePayRefundPrice",
                        width: 120,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "使用车辆退款额度",
                        dataField: "useVehicleRefundQuota",
                        width: 140,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "退款金额",
                        dataField: "refundAmount",
                        width: 120,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "抵扣欠款金额",
                        dataField: "deductibleAmount",
                        width: 120,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "经办人",
                        dataField: "operatorName",
                        width: 120,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "创建人",
                        dataField: "createName",
                        width: 120,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "创建时间",
                        dataField: "createDateStr",
                        width: 140,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "是否红冲",
                        dataField: "isReverseStr",
                        width: 100,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "备注",
                        dataField: "note",
                        width: 160,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        width: 60,
                        isShow: true,
                        isFixed: true
                    }
                ]
            };
            $scope.tableMaterialConfig = {
                scrollWidth: 1270,
                tableCol: [
                    {
                        type: "",
                        name: "零件编号",
                        dataField: "materialNo",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "零件中文名",
                        dataField: "materialDesc",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "单位",
                        dataField: "unit",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "单价",
                        dataField: "price",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        isInput: false
                    },
                    {
                        type: "",
                        name: "退货数量",
                        dataField: "returnQuantity",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                        isInput: true
                    },
                    {
                        type: "",
                        name: "可退数量",
                        dataField: "remainReturnQty",
                        width: 100,
                        isShow: true,
                        isFixed: false
                    },
                ]
            };
            // 是否红冲筛选列表
            $scope.isReverseList = [
                {id: 0, name: "否"},
                {id: 1, name: "是"}
            ];
            // 设置表格宽度
            $scope.setFixedWidth = function () {
                $scope.tbStyle = {
                    billFixedWidth: {left: $scope.tableConfig.fixedWidth + "px"}
                };
            };
            // 设置按钮权限
            function setBtnPermission() {
                for (var key in btnPermissionCode) {
                    $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                }
            }
            // 列表导出的url和参数
            $scope.exportParam = {
                sectionUrl: ybHttp.RequestUrl("device", UrlObj.export),
                sectionParam: {ids: []},
                allUrl: ybHttp.RequestUrl("device", UrlObj.exportAll)
            };
            $scope.detailInfo = {};         // 详情信息
            $scope.dataList = [];          // 退款单列表
            $scope.condition = {};         // 搜索条件
            $scope.datePickerFlag = [false, false];
            // 切换时间选择器
            $scope.switchDataPicker = function (index) {
                $scope.datePickerFlag = [false, false];
                if (angular.isDefined(index)) {
                    $scope.datePickerFlag[index] = true;
                }
            };
            $scope.checkDate = function (obj, startFiled, endFiled) {
                var timeFormatObj = ybWidget.CheckDate(obj[startFiled], obj[endFiled]);
                if (!!timeFormatObj.tStart) {
                    obj[startFiled] = timeFormatObj.tStart;
                }
                if (!!timeFormatObj.tEnd) {
                    obj[endFiled] = timeFormatObj.tEnd;
                }
            };
            // 切换标签页
            $scope.changeTab = function (index) {
                angular.forEach($scope.activeFlag, function (activeFlag) {
                    activeFlag = false;
                });
                $scope.activeFlag[index] = true;
                if (index === 0) {
                    $scope.detailInfo = {};
                    $scope.submitted = false;
                }
            };
            // 选择所有列
            $scope.selectAll = function () {
                for (var i = 0; i < $scope.dataList.length; i++) {
                    $scope.dataList[i].isChecked = $scope.markInfo.allChecked;
                }
                getBillIds();
            };
            // 选择一列
            $scope.selectSingle = function (item) {
                var selectAll = false;
                if (!item.isChecked) {
                    selectAll = false;
                } else {
                    selectAll = checkAll($scope.dataList);
                }
                $scope.markInfo.allChecked = selectAll;
                getBillIds();
            };
            // 检查是否全部已选
            function checkAll(list) {
                var selectAll = false;
                for (var i = 0, len = list.length; i < len; i++) {
                    if (!list[i].isChecked) {
                        selectAll = false;
                        break;
                    }
                    selectAll = true;
                }
                return selectAll;
            }
            // 获取已选择的预收款id  导出要用
            function getBillIds() {
                $scope.exportParam.sectionParam.ids = [];
                angular.forEach($scope.dataList, function (item) {
                    if (!!item.isChecked) {
                        $scope.exportParam.sectionParam.ids.push(item.id);
                    }
                });
            }
            // 取消
            $scope.cancel = function () {
                $scope.changeTab(0);
            };

            $scope.tdClick = function (item, fnType) {
                switch (fnType) {
                    case "viewDetail":
                        viewDetail(item);
                        break;
                    default:
                        break;
                }
            };

            function viewDetail (item) {
                getReturnDetail(item).then(function (data) {
                    if (data) {
                        $scope.changeTab(1);
                    }
                })
            }

            // 获取退货单详情
            function getReturnDetail (item) {
                var url = '/agentReturnDetail/item';
                return ybHttp.Get('device', url, {returnIds: [item.refundId]}).then(function (res) {
                    if (res.code !== 0) {
                        ybWidget.ShowMessage(res, MESG_TYPE.Error);
                        return false;
                    }
                    if (!res.value || res.value.length <= 0) return false;
                    var detailInfo = res.value[0];
                    detailInfo.inboundStatusStr = $filter("ProgressStatus")(detailInfo.inboundStatus, "inDepot");
                    detailInfo.saleTypeStr = $filter("BillTypeStatus")(detailInfo.saleType);
                    detailInfo.statusStr = $filter("ProgressStatus")(detailInfo.status, "returnAudit");
                    detailInfo.checkStateStr = $filter("ProgressStatus")(detailInfo.checkState, "checkState");
                    detailInfo.createTimeStr = $filter("YbDate")(detailInfo.createTime, 'yyyy-MM-dd HH:mm:ss');
                    detailInfo.auditTimeStr = $filter("YbDate")(detailInfo.auditTime, 'yyyy-MM-dd HH:mm:ss');
                    detailInfo.auditTimeStr = $filter("YbDate")(detailInfo.auditTime, 'yyyy-MM-dd HH:mm:ss');
                    $scope.detailInfo = detailInfo;
                    return true;
                })
            }

            $scope.search = function (curPage) {
                $scope.markInfo.allChecked = false;
                if (curPage) $scope.pageInfo.CurPage = curPage;
                getDataList();
            };

            // 获取退款列表
            function getDataList () {
                //遍历搜索条件对象里的空值并删除  不然搜索不出数据
                Object.keys($scope.condition).forEach(function (key) {
                    if (!$scope.condition[key] && $scope.condition[key] !== 0) delete $scope.condition[key];
                });
                var filters = angular.copy($scope.condition);
                var params = {
                    filters: filters,
                    pageSize: $scope.pageInfo.pageSize,
                    pageNum: $scope.pageInfo.curPage
                };
                request('list', 'post', params).then(function (data) {
                    if (!data) {
                        return;
                    }
                    angular.forEach(data.value.list, function (item) {
                        item.isChecked = false;
                        item.createDateStr = $filter("YbDate")(item.createDate, 'yyyy-MM-dd HH:mm:ss');
                        item.isReverseStr = $filter('TrueOrFalse')(item.isReverse, 'normal');
                    });
                    $scope.pageInfo.totalRows = data.value.total;
                    $scope.pageInfo.totalPages = data.value.pages;
                    $scope.dataList = data.value.list;
                })
            }

            // 红冲
            $scope.reverse = function (item) {
                ybWidget.ShowMessage("单据红冲不可恢复，确定红冲？", MESG_TYPE.Ask).then(function () {
                    request('reverse', 'post', item).then(function (data) {
                        if (data) {
                            $scope.search(1);
                        }
                    })
                });
            };

            /**
             * 公共请求方法
             * @param urlKey 请求url的UrlObj对象的键值
             * @param type 请求类型RequestTypeObj对象的键值
             * @param param 请求的参数
             */
            function request (urlKey, type, param) {
                var url = UrlObj[urlKey];
                var method = RequestTypeObj[type];
                if (!url || !method) return false;
                return ybHttp[method]('device', url, param).then(function (res) {
                    if (res.code !== 0) {
                        ybWidget.ShowMessage(res, MESG_TYPE.Error);
                        return false;
                    }
                    return res;
                });
            }

            // 初始化页面信息
            (function () {
                getDataList();
                UserContextService.SetBtnPermission(setBtnPermission);
                $scope.setFixedWidth();
            })()
        }])
    ;
})(window, window.angular);